// ===== 管理员设置系统 =====

let settings = {};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    try {
        loadSettings();
        initializeSettings();
        setupEventListeners();
        showTab('general');
        console.log('管理员设置页面初始化完成');
    } catch (error) {
        console.error('设置页面初始化失败:', error);
        showNotification('页面初始化失败，请刷新重试', 'error');
    }
});

// ===== 设置数据管理 =====

function loadSettings() {
    try {
        const savedSettings = localStorage.getItem('adminSettings');
        settings = savedSettings ? JSON.parse(savedSettings) : getDefaultSettings();
        console.log('已加载设置数据:', settings);
    } catch (error) {
        console.error('加载设置数据失败:', error);
        settings = getDefaultSettings();
    }
}

function getDefaultSettings() {
    return {
        // 基本设置
        siteName: '加强附魔金苹果模组',
        siteDescription: '为 Minecraft 1.21.8 提供强大的附魔金苹果功能',
        adminEmail: 'admin@example.com',
        timezone: 'Asia/Shanghai',
        language: 'zh-CN',
        
        // 外观设置
        theme: 'dark',
        primaryColor: '#4ade80',
        backgroundColor: '#0a0a0a',
        enableAnimations: true,
        showLogo: true,
        logoSize: 'medium',
        
        // 通知设置
        emailNotifications: true,
        newFeedbackNotification: true,
        dailyReport: false,
        notificationSound: true,
        pushNotifications: false,
        
        // 安全设置
        enableTwoFactor: false,
        sessionTimeout: 30,
        autoBackup: true,
        loginAttempts: 5,
        ipWhitelist: '',
        
        // 备份设置
        autoBackupInterval: 24,
        backupRetention: 7,
        backupLocation: 'local',
        encryptBackups: true,
        cloudBackupProvider: 'none'
    };
}

function saveSettings() {
    try {
        localStorage.setItem('adminSettings', JSON.stringify(settings));
        console.log('设置已保存:', settings);
        showNotification('设置已保存', 'success');
        applySettings();
    } catch (error) {
        console.error('保存设置失败:', error);
        showNotification('保存设置失败', 'error');
    }
}

function resetSettings() {
    if (confirm('确定要重置所有设置到默认值吗？此操作不可撤销。')) {
        settings = getDefaultSettings();
        initializeSettings();
        saveSettings();
        showNotification('设置已重置到默认值', 'info');
    }
}

// ===== 界面初始化 =====

function initializeSettings() {
    try {
        // 基本设置
        setValue('siteName', settings.siteName || '');
        setValue('siteDescription', settings.siteDescription || '');
        setValue('adminEmail', settings.adminEmail || '');
        setValue('timezone', settings.timezone || 'Asia/Shanghai');
        setValue('language', settings.language || 'zh-CN');
        
        // 外观设置
        setValue('theme', settings.theme || 'dark');
        setValue('primaryColor', settings.primaryColor || '#4ade80');
        setValue('backgroundColor', settings.backgroundColor || '#0a0a0a');
        setChecked('enableAnimations', settings.enableAnimations !== false);
        setChecked('showLogo', settings.showLogo !== false);
        setValue('logoSize', settings.logoSize || 'medium');
        
        // 通知设置
        setChecked('emailNotifications', settings.emailNotifications !== false);
        setChecked('newFeedbackNotification', settings.newFeedbackNotification !== false);
        setChecked('dailyReport', settings.dailyReport === true);
        setChecked('notificationSound', settings.notificationSound !== false);
        setChecked('pushNotifications', settings.pushNotifications === true);
        
        // 安全设置
        setChecked('enableTwoFactor', settings.enableTwoFactor === true);
        setValue('sessionTimeout', settings.sessionTimeout || 30);
        setChecked('autoBackup', settings.autoBackup !== false);
        setValue('loginAttempts', settings.loginAttempts || 5);
        setValue('ipWhitelist', settings.ipWhitelist || '');
        
        // 备份设置
        setValue('autoBackupInterval', settings.autoBackupInterval || 24);
        setValue('backupRetention', settings.backupRetention || 7);
        setValue('backupLocation', settings.backupLocation || 'local');
        setChecked('encryptBackups', settings.encryptBackups !== false);
        setValue('cloudBackupProvider', settings.cloudBackupProvider || 'none');
        
        // 更新显示状态
        updateSettingsDisplay();
        
        console.log('设置初始化完成');
    } catch (error) {
        console.error('设置初始化过程中出错:', error);
    }
}

function setValue(id, value) {
    const element = document.getElementById(id);
    if (element) {
        element.value = value;
    }
}

function setChecked(id, checked) {
    const element = document.getElementById(id);
    if (element && (element.type === 'checkbox' || element.type === 'radio')) {
        element.checked = checked;
    }
}

function updateSettingsDisplay() {
    // 更新颜色预览
    updateColorPreviews();
    
    // 更新依赖项状态
    updateDependentSettings();
    
    // 应用当前设置到界面
    applySettings();
}

function updateColorPreviews() {
    const primaryColor = document.getElementById('primaryColor');
    const backgroundColor = document.getElementById('backgroundColor');
    
    if (primaryColor && primaryColor.value) {
        primaryColor.style.borderColor = primaryColor.value;
        // 更新CSS变量
        document.documentElement.style.setProperty('--primary-color', primaryColor.value);
    }
    
    if (backgroundColor && backgroundColor.value) {
        backgroundColor.style.borderColor = backgroundColor.value;
        // 更新CSS变量
        document.documentElement.style.setProperty('--background-color', backgroundColor.value);
    }
}

function updateDependentSettings() {
    // 通知设置依赖
    const emailNotifications = document.getElementById('emailNotifications');
    const newFeedbackNotification = document.getElementById('newFeedbackNotification');
    const dailyReport = document.getElementById('dailyReport');
    
    if (emailNotifications && newFeedbackNotification) {
        newFeedbackNotification.disabled = !emailNotifications.checked;
    }
    if (emailNotifications && dailyReport) {
        dailyReport.disabled = !emailNotifications.checked;
    }
    
    // 备份设置依赖
    const autoBackup = document.getElementById('autoBackup');
    const autoBackupInterval = document.getElementById('autoBackupInterval');
    const backupRetention = document.getElementById('backupRetention');
    
    if (autoBackup && autoBackupInterval) {
        autoBackupInterval.disabled = !autoBackup.checked;
    }
    if (autoBackup && backupRetention) {
        backupRetention.disabled = !autoBackup.checked;
    }
    
    // 云备份设置
    const backupLocation = document.getElementById('backupLocation');
    const cloudBackupProvider = document.getElementById('cloudBackupProvider');
    
    if (backupLocation && cloudBackupProvider) {
        cloudBackupProvider.disabled = backupLocation.value !== 'cloud';
    }
}

// ===== 标签页管理 =====

function showTab(tabName) {
    // 隐藏所有设置区域
    const sections = document.querySelectorAll('.settings-section');
    sections.forEach(section => {
        section.classList.remove('active');
    });
    
    // 移除所有导航项的激活状态
    const navItems = document.querySelectorAll('.settings-nav-item');
    navItems.forEach(item => {
        item.classList.remove('active');
    });
    
    // 显示选中的设置区域
    const targetSection = document.getElementById(tabName);
    const targetNavItem = document.querySelector(`[onclick*="${tabName}"]`);
    
    if (targetSection) {
        targetSection.classList.add('active');
    }
    if (targetNavItem) {
        targetNavItem.classList.add('active');
    }
}

// 添加兼容函数
function switchSettingsTab(tabName) {
    showTab(tabName);
}

// ===== 事件处理 =====

function setupEventListeners() {
    // 输入框变化事件
    const inputs = document.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
        if (input.id) {  // 只处理有ID的元素
            input.addEventListener('change', function() {
                updateSettingValue(this.id, this.type === 'checkbox' ? this.checked : this.value);
                updateDependentSettings();
            });
            
            // 颜色输入框实时预览
            if (input.type === 'color') {
                input.addEventListener('input', function() {
                    updateColorPreviews();
                });
            }
        }
    });
    
    // 键盘快捷键
    document.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key === 's') {
            e.preventDefault();
            saveSettings();
        }
    });
}

function updateSettingValue(key, value) {
    settings[key] = value;
    console.log('设置已更新:', key, '=', value);
}

// ===== 设置应用 =====

function applySettings() {
    // 应用主题
    applyTheme();
    
    // 应用颜色
    applyColors();
    
    // 应用动画
    applyAnimations();
    
    // 应用其他设置
    applyMiscSettings();
}

function applyTheme() {
    const theme = settings.theme;
    document.body.className = theme === 'light' ? 'light-theme' : '';
    
    if (theme === 'light') {
        document.body.style.background = 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 50%, #cbd5e1 100%)';
        document.body.style.color = '#1f2937';
    } else {
        document.body.style.background = 'linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 50%, #16213e 100%)';
        document.body.style.color = '#ffffff';
    }
}

function applyColors() {
    const root = document.documentElement;
    root.style.setProperty('--primary-color', settings.primaryColor);
    root.style.setProperty('--background-color', settings.backgroundColor);
}

function applyAnimations() {
    const animationStyle = settings.enableAnimations ? '' : 'none';
    document.body.style.setProperty('--animation-duration', animationStyle);
}

function applyMiscSettings() {
    // 应用语言设置
    if (settings.language === 'en') {
        document.documentElement.lang = 'en';
    }
    
    // 应用Logo显示设置
    const logos = document.querySelectorAll('.logo, .sidebar-logo');
    logos.forEach(logo => {
        logo.style.display = settings.showLogo ? 'block' : 'none';
    });
}

// ===== 具体功能实现 =====

function testEmailSettings() {
    const adminEmail = settings.adminEmail;
    
    if (!adminEmail || !validateEmail(adminEmail)) {
        showNotification('请先设置有效的管理员邮箱', 'warning');
        return;
    }
    
    showNotification('正在发送测试邮件...', 'info');
    
    // 模拟发送邮件
    setTimeout(() => {
        showNotification(`测试邮件已发送到 ${adminEmail}`, 'success');
    }, 2000);
}

function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

function clearCache() {
    if (confirm('确定要清除所有缓存数据吗？这可能会影响网站性能。')) {
        // 清除缓存逻辑
        localStorage.removeItem('modFeedbacks');
        
        showNotification('缓存已清除', 'success');
    }
}

function exportSettings() {
    const settingsData = JSON.stringify(settings, null, 2);
    const blob = new Blob([settingsData], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `admin-settings-${new Date().toISOString().split('T')[0]}.json`;
    link.style.display = 'none';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(url);
    showNotification('设置已导出', 'success');
}

function importSettings() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    input.style.display = 'none';
    
    input.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        reader.onload = function(e) {
            try {
                const importedSettings = JSON.parse(e.target.result);
                
                // 验证设置格式
                if (validateSettingsFormat(importedSettings)) {
                    settings = { ...getDefaultSettings(), ...importedSettings };
                    initializeSettings();
                    saveSettings();
                    showNotification('设置已导入', 'success');
                } else {
                    showNotification('设置文件格式无效', 'error');
                }
            } catch (error) {
                console.error('导入设置失败:', error);
                showNotification('导入设置失败', 'error');
            }
        };
        
        reader.readAsText(file);
    });
    
    document.body.appendChild(input);
    input.click();
    document.body.removeChild(input);
}

function validateSettingsFormat(settings) {
    const requiredKeys = ['siteName', 'theme', 'primaryColor'];
    return requiredKeys.every(key => key in settings);
}

function createBackup() {
    showNotification('正在创建备份...', 'info');
    
    const backupData = {
        settings: settings,
        feedbacks: JSON.parse(localStorage.getItem('modFeedbacks') || '[]'),
        timestamp: new Date().toISOString(),
        version: '1.0.0'
    };
    
    const backupJson = JSON.stringify(backupData, null, 2);
    const blob = new Blob([backupJson], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `backup-${new Date().toISOString().split('T')[0]}.json`;
    link.style.display = 'none';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    URL.revokeObjectURL(url);
    showNotification('备份已创建并下载', 'success');
}

function restoreBackup() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    input.style.display = 'none';
    
    input.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        if (confirm('恢复备份将覆盖所有当前数据，确定继续吗？')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const backupData = JSON.parse(e.target.result);
                    
                    if (backupData.settings && backupData.feedbacks) {
                        // 恢复设置
                        settings = backupData.settings;
                        localStorage.setItem('adminSettings', JSON.stringify(settings));
                        
                        // 恢复反馈数据
                        localStorage.setItem('modFeedbacks', JSON.stringify(backupData.feedbacks));
                        
                        // 重新初始化界面
                        initializeSettings();
                        
                        showNotification('备份已恢复', 'success');
                        setTimeout(() => {
                            location.reload();
                        }, 2000);
                    } else {
                        showNotification('备份文件格式无效', 'error');
                    }
                } catch (error) {
                    console.error('恢复备份失败:', error);
                    showNotification('恢复备份失败', 'error');
                }
            };
            
            reader.readAsText(file);
        }
    });
    
    document.body.appendChild(input);
    input.click();
    document.body.removeChild(input);
}

function checkSystemStatus() {
    showNotification('正在检查系统状态...', 'info');
    
    // 模拟系统检查
    setTimeout(() => {
        const status = {
            storage: Math.floor(Math.random() * 30) + 10,
            memory: Math.floor(Math.random() * 20) + 70,
            uptime: '15天 8小时 32分钟',
            errors: Math.floor(Math.random() * 5)
        };
        
        const statusMessage = `
系统状态检查完成：
- 存储使用率: ${status.storage}%
- 内存使用率: ${status.memory}%
- 运行时间: ${status.uptime}
- 错误数量: ${status.errors}
        `.trim();
        
        showNotification(statusMessage, status.errors > 2 ? 'warning' : 'success');
    }, 2000);
}

function optimizeDatabase() {
    if (confirm('数据库优化可能需要几分钟时间，期间网站可能响应较慢，确定继续吗？')) {
        showNotification('正在优化数据库...', 'info');
        
        // 模拟数据库优化
        setTimeout(() => {
            showNotification('数据库优化完成，性能已提升', 'success');
        }, 3000);
    }
}

// ===== 通知系统 =====

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    
    const icon = type === 'success' ? 'check' : type === 'error' ? 'times' : type === 'warning' ? 'exclamation' : 'info';
    
    notification.innerHTML = `
        <i class="fas fa-${icon}"></i>
        <span>${message}</span>
        <button class="notification-close" onclick="closeNotification(this)">
            <i class="fas fa-times"></i>
        </button>
    `;
    
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${getNotificationColor(type)};
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 500;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 400px;
        word-wrap: break-word;
        white-space: pre-line;
    `;
    
    const closeButton = notification.querySelector('.notification-close');
    closeButton.style.cssText = `
        background: none;
        border: none;
        color: rgba(255, 255, 255, 0.8);
        cursor: pointer;
        font-size: 0.9rem;
        margin-left: auto;
        padding: 5px;
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动关闭
    setTimeout(() => {
        closeNotification(closeButton);
    }, message.length > 50 ? 6000 : 4000);
}

function getNotificationColor(type) {
    const colors = {
        success: '#4ade80',
        error: '#ef4444',
        warning: '#f59e0b',
        info: '#3b82f6'
    };
    return colors[type] || colors.info;
}

function closeNotification(button) {
    const notification = button.closest('.notification');
    if (notification) {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }
}

// ===== 侧边栏管理 =====

function toggleSidebar() {
    const sidebar = document.querySelector('.admin-sidebar');
    if (sidebar) {
        sidebar.classList.toggle('show');
    }
}

function logout() {
    if (confirm('确定要退出登录吗？')) {
        showNotification('正在退出...', 'info');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 1000);
    }
}

// ===== 快捷键支持 =====

document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + S 保存设置
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        saveSettings();
    }
    
    // Ctrl/Cmd + R 重置设置
    if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
        e.preventDefault();
        resetSettings();
    }
    
    // Esc 关闭通知
    if (e.key === 'Escape') {
        const notifications = document.querySelectorAll('.notification');
        notifications.forEach(notification => {
            const closeBtn = notification.querySelector('.notification-close');
            if (closeBtn) {
                closeNotification(closeBtn);
            }
        });
    }
});